package com.guodu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.guodu.util.Constant;

public class FileLocator {

	public static final String[] FILE_TYPE_ARRAY = { "doc", "docx", "xls",
			"xlsx", "ppt", "pptx", "txt", "zip", "rar", "pdf" };

	public static final int FILE_MAX_SIZE = 5;

	public static final int FILE_MAX_SIZE_UNIT = 1024 * 1024 * FILE_MAX_SIZE;

	private static Logger logger = Logger
			.getLogger(FileLocator.class.getName());

	public static File getConfFile(String fileName) {
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();

		URL confURL = classLoader.getResource(fileName);
		{
			File file1 = new File(confURL.getFile());
			if (file1.isFile()) {
				logger.debug("Locate file: " + confURL.getFile());
				return file1;
			} else {
				logger.debug(" it is not a file: " + confURL.getFile());
				return null;
			}
		}
	}

	public static boolean isLegal(String fileName) {
		int ind = fileName.lastIndexOf(".");
		if (ind == -1) {
			return false;
		}
		String fileType = fileName.substring(ind + 1, fileName.length())
				.toLowerCase();
		int isExist = -1;
		for (int i = 0; i < FILE_TYPE_ARRAY.length; i++) {
			if (fileType.equals(FILE_TYPE_ARRAY[i])) {
				isExist = i;
			}
		}
		if (isExist == -1) {
			return false;
		}
		return true;
	}

	public synchronized static boolean synchFile(String sessionId,
			Long userId, long creatTime, int type) {
		File adminFile = FileLocator
				.getConfFile(Constant.ADMIN_ONLINE_FILE_PROPERTIES);
		Thread thread = Thread.currentThread();
		System.out.println("[" + sessionId + "," + thread.getName() + "]="
				+ adminFile.getPath());
		Properties properties = new Properties();
		FileOutputStream output = null;
		boolean result = true;
		try {
			switch (type) {
			case 1:
				output = new FileOutputStream(adminFile, true);
				String adminStr = sessionId + "=" + userId + "&&" + creatTime
						+ "\n";
				output.write(adminStr.getBytes());
				output.flush();
				break;
			case 2:
				properties.load(new FileInputStream(adminFile));
				output = new FileOutputStream(adminFile, false);

				Set<Entry<Object, Object>> keySet = properties.entrySet();
				Iterator<Entry<Object, Object>> iter = keySet.iterator();
				String tempStr = "";
				Entry<Object, Object> entry = null;
				while (iter.hasNext()) {
					entry = iter.next();
					if (!sessionId.equals(entry.getKey().toString())) {
						tempStr = tempStr + entry.getKey() + "="
								+ entry.getValue() + "\n";
					}
				}
				output.write(tempStr.getBytes());
				output.flush();

				break;
			case 3:
				String userTempId = "";
				long logTempTime;

				properties.load(new FileInputStream(adminFile));
				output = new FileOutputStream(adminFile, false);

				keySet = properties.entrySet();
				iter = keySet.iterator();
				tempStr = "";
				entry = null;
				String[] value;
				while (iter.hasNext()) {
					entry = iter.next();
					value = entry.getValue().toString().split("&&");
					userTempId = value[0];
					logTempTime = new Long(value[1]);

					if (userTempId.equals(userId.toString())) {
						if (logTempTime > creatTime) {
							tempStr = tempStr + entry.getKey() + "="
									+ entry.getValue() + "\n";
							result = false;
						}
					} else {
						tempStr = tempStr + entry.getKey() + "="
								+ entry.getValue() + "\n";
					}
				}
				if (result) {
					tempStr = tempStr + sessionId + "=" + userId + "&&"
							+ creatTime + "\n";
				}

				output.write(tempStr.getBytes());
				output.flush();
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

}
